package com.ljd.server.controller;

import com.ljd.server.pojo.Admin;
import com.ljd.server.pojo.AdminLoginParam;
import com.ljd.server.pojo.RespBean;
import com.ljd.server.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 登录
 *
 * @author ljd on 2022/1/22
 * @PACKAGE_NAME: com.ljd.server.controller
 * @PROJECT_NAME: yeb
 */
@Api(tags = "LoginController")
@RestController
public class LoginController {

    @Autowired
    private IAdminService adminService;



    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request) {

        return adminService.login(adminLoginParam.getUsername(),adminLoginParam.getPassword(),adminLoginParam.getCode(),request);
    }


    /**
     * 当我们登录成功之后就将用户信息存储到了springsecurity,此时单元方法就可以声明Principal类型的形参获取用户信息了
     * @param principal
     * @return
     */
    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal) {
        if (null == principal) {
            return null;
        }
        String username = principal.getName();
        Admin admin = adminService.getAdminByUserName(username);
        admin.setPassword(null);
        admin.setRoles(adminService.getRoles(admin.getId()));
        return admin;
    }


    /**
     * 注意: 这里是前后端分离项目,前端需要退出登录,我们只需要给他一个返回,前端接收到返回成功后会将token删除,再次访问时就会被
     * 我们的拦截器拦截
     * @return
     */
    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout() {
        return RespBean.success("注销成功!!");
    }
}
